<?php

namespace App\Jobs;

use App\Service\news\SendNoticeService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * 消息推送队列
 */
class NewsSendQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $timeout = 60;

    protected array $retry_map = [
        '1' => 10,
        '2' => 30,
        '3' => 120
    ];

    private int $newsId;

    /**
     * Create a new job instance.
     */
    public function __construct($newsId)
    {
        if (!$newsId) {
            log::error(Carbon::now()->toDateTimeString() . ' 消息推送异常: 缺少参数');
        }
        $this->newsId = $newsId;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $sendService = new SendNoticeService();
            $sendService->send($this->newsId);
            Log::info(Carbon::now()->toDateTimeString() . ' 消息推送结束: 消息id: ['.$this->newsId.']');
        } catch (\Throwable $e) {
            log::error(Carbon::now()->toDateTimeString() . ' 消息推送异常:'.$e->getMessage());
            $this->release($this->retry_map[$this->attempts()]);
        }
    }


    /**
     * 失败重试
     * @param $exception
     * @return void
     */
    public function failed($exception): void
    {
        $sendService = new SendNoticeService();
        $sendService->delete($this->newsId);
        Log::error(Carbon::now()->toDateTimeString() . ' 消息推送异常重试:' . $exception->getMessage());
    }
}
